package com.ihr360.commons.serializer.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.apache.commons.beanutils.MethodUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 *
 */
public class EnumDataSerializer extends StdSerializer<Enum> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public EnumDataSerializer() {
        this(Enum.class);
    }

    public EnumDataSerializer(Class<Enum> t) {
        super(t);
    }

    @Override
    public void serialize(Enum value, JsonGenerator generator, SerializerProvider provider) throws IOException {
        if (value == null) {
            return;
        }
        Class clazz = value.getClass();
        Method m = MethodUtils.getAccessibleMethod(clazz, "getTitle", new Class[0]);
        generator.writeStartObject();
        generator.writeFieldName("id");
        generator.writeString(value.name());
        if (null != m) {
            try {
                Object e = m.invoke(value);
                generator.writeFieldName("title");
                generator.writeObject(e);
            } catch (Exception var7) {
                this.logger.info("process " + value.getClass() + " value of method " + m.getName() + " failure", var7);
            }
        }
        generator.writeEndObject();
    }
}